package com.wonderplay.engine;


public class MainProcess implements Runnable {

	// refresh time in ms
	long refreshTime = 50;
	Thread gameThread;
	
	GameEngine gameEngine;
	
	public enum GAME_STATUS {INIT, STOP, ONGOING};
	
	GAME_STATUS status;

	
	public MainProcess(long refreshTime, GameEngine gameEngine){
		this.refreshTime = refreshTime;
		this.gameEngine = gameEngine;
		this.status = GAME_STATUS.ONGOING;
	}
	
	public void start() {
		status = GAME_STATUS.ONGOING;
		
		gameThread = new Thread(this);
		gameThread.setName("GameThread");
		gameThread.start();
		
	}
	
	public void run() {

		long startTime, endTime, sleepTime;
		while (status == GAME_STATUS.ONGOING) {
			startTime = System.currentTimeMillis();

			gameEngine.doStep();
			
			endTime = System.currentTimeMillis();

			sleepTime = refreshTime - (endTime - startTime);
			sleepTime = sleepTime > 0 ? sleepTime : 0;
			
			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void changeStatus(GAME_STATUS newStatus){
		this.status = newStatus;
	}

}
